// pages/shopCode/shopCode.js
import api from "../../api/index";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    shopID: null,
    shopData: {
      name: "shop_id",
      list: [],
    },

    detail: null,

    isOpen: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      list: [],
      shopID: wx.getStorageSync("shopID"),
    });
    this.getShopList();
    this.getQrcolor();
  },

  getShopValue(e) {
    this.setData({
      detail: null,
      shopID: e.detail.value,
    });
    this.getQrcolor();
  },
  getShopList() {
    api.apiStoreShopList().then((res) => {
      this.setData({
        "shopData.list": res.data.list,
      });
    });
  },
  getQrcolor() {
    let { list, shopID } = this.data;
    this.setData({
      isLoading: true,
    });
    api
      .apiStoreQrcode({
        shop_id: shopID,
      })
      .then((res) => {
        if (shopID !== this.data.shopID) return;
        this.setData({ detail: res.data });
      })
      .finally((_) => {
        this.setData({
          isLoading: false,
        });
      });
  },

  async saveImageWithAuthCheck() {
    try {
      // 1. 检查权限
      const hasAuth = await this.checkPhotoAlbumAuth();
      if (!hasAuth) {
        // 2. 如果没有权限，引导用户开启
        await this.showAuthModal();
        return;
      }

      // 3. 下载并保存图片
      this.saveNetworkImage();
    } catch (error) {
      wx.showToast({ title: "保存失败", icon: "none" });
    }
  },
  saveNetworkImage() {
    wx.downloadFile({
      url: this.data.detail.qrcode_image, // 网络图片地址
      success: (res) => {
        if (res.statusCode === 200) {
          this.saveImageToPhotosAlbum(res.tempFilePath);
        }
      },
      fail: (err) => {
        wx.showToast({ title: "下载失败", icon: "none" });
      },
    });
  },

  saveImageToPhotosAlbum(filePath) {
    wx.saveImageToPhotosAlbum({
      filePath: filePath,
      success: () => {
        wx.showToast({ title: "保存成功" });
      },
      fail: (err) => {
        if (err.errMsg.includes("auth")) {
          this.showAuthGuide();
        } else {
          wx.showToast({ title: "保存失败", icon: "none" });
        }
      },
    });
  },
  // 显示权限引导弹窗
  showAuthModal() {
    return new Promise((resolve) => {
      wx.showModal({
        title: "权限提示",
        content: "需要您授权保存图片到相册",
        confirmText: "去设置",
        confirmColor: "#73F0EA",
        success: (res) => {
          if (res.confirm) {
            wx.openSetting({
              success: (settingRes) => {
                if (settingRes.authSetting["scope.writePhotosAlbum"]) {
                  resolve(true);
                } else {
                  resolve(false);
                }
              },
            });
          } else {
            resolve(false);
          }
        },
      });
    });
  },
  checkPhotoAlbumAuth() {
    return new Promise((resolve) => {
      wx.getSetting({
        success: (res) => {
          const authSetting = res.authSetting;
          if (authSetting["scope.writePhotosAlbum"] === false) {
            resolve(false);
          } else {
            resolve(true);
          }
        },
        fail: () => resolve(false),
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
